import { Client, Account, ID, Databases, Query } from 'appwrite'

import { Server } from '@configs/server.js'

const client = new Client()
  .setEndpoint(Server.endpoint)
  .setProject(Server.project)
const databases = new Databases(client)
const account = new Account(client)

/** 创建账户 */
export const createAccountApi = async ({ email, name }) => {
  // 二级账户创建
  // const accountRes = await account.create(ID.unique(), email, password, name,role)
  const accountRes = await account.create(
    ID.unique(),
    email,
    '12345678',
    name,
    { label: ['worker'] }
  )
  console.log('accountRes', accountRes)
  // 二级账户专属表（所属社区、小区）
  return await databases.createDocument(
    Server.databaseID,
    Server.collection_sub_adminID,
    ID.unique(),
    JSON.stringify({
      name,
      email,
    })
  )
}

/** 获取账户列表 分页 */
export const accountListApi = async ({ q, perPage, offsetPage }) => {
  let condition = [Query.limit(perPage), Query.offset(offsetPage)]
  if (!q) {
    condition = [...condition]
  } else {
    condition = [...condition, Query.search('name', q)]
  }
  return await databases.listDocuments(
    Server.databaseID,
    Server.collection_sub_adminID,
    condition
  )
}

/** 编辑账户列表 */
export const editAccountApi = async ({ $id, name, email }) => {
  return await databases.updateDocument(
    Server.databaseID,
    Server.collection_sub_adminID,
    $id,
    {
      name,
      email,
    }
  )
}

export const deleteAccountApi = async ($id) => {
  return await databases.deleteDocument(
    Server.databaseID,
    Server.collection_sub_adminID,
    $id
  )
}
